const db = require('../config/db');
const { success, fail } = require('../utils/response');

// 订单状态常量（上移到文件顶部，避免未定义引用）
const ORDER_STATUS = {
  MAKING: 0,
  PREORDER: 1,
  COMPLETED: 2
};

exports.createOrder = async (req, res) => {
  const { items } = req.body;
  
  // 检查商品是否存在，同时取出价格与图片
  const productIds = items.map(item => item.product_id);
  const [productRows] = await db.query('SELECT id, price, image FROM Product WHERE id IN (?)', [productIds]);
  
  const productMap = {};
  productRows.forEach(product => {
    productMap[product.id] = product;
  });
  
  for (const item of items) {
    const product = productMap[item.product_id];
    if (!product) return res.json(fail(`商品ID ${item.product_id} 不存在`));
  }
  
  // 计算总金额 & 选取封面图
  let totalAmount = 0;
  let coverImage = null;
  for (const item of items) {
    const p = productMap[item.product_id];
    totalAmount += p.price * item.quantity;
    if (!coverImage && p.image) coverImage = p.image;
  }

  // 开始事务
  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();

    // 创建订单：写入 image 列
    const [orderResult] = await connection.query(
      'INSERT INTO `Order` (user_id, total_amount, order_date, status, image) VALUES (?, ?, NOW(), ?, ?)',
      [req.user.id, totalAmount, ORDER_STATUS.PREORDER, coverImage]
    );
    const order_id = orderResult.insertId;

    // 添加订单商品
    for (const item of items) {
      await connection.query(
        'INSERT INTO Order_Product (order_id, product_id, quantity) VALUES (?, ?, ?)',
        [order_id, item.product_id, item.quantity]
      );
    }

    // 清空购物车
    await connection.query('DELETE FROM Cart WHERE user_id=?', [req.user.id]);

    await connection.commit();
    res.json(success({ order_id, total_amount: totalAmount, order_date: new Date().toISOString(), image: coverImage }));
  } catch (error) {
    await connection.rollback();
    console.error(error);
    res.json(fail('创建订单失败'));
  } finally {
    connection.release();
  }
};

exports.getOrders = async (req, res) => {
  const [rows] = await db.query('SELECT * FROM `Order` WHERE user_id=? ORDER BY order_date DESC', [req.user.id]);
  res.json(success(rows));
};

exports.getOrderById = async (req, res) => {
  const { id } = req.params;
  const [orderRows] = await db.query('SELECT * FROM `Order` WHERE id=? AND user_id=?', [id, req.user.id]);
  if (!orderRows.length) return res.json(fail('订单不存在'));

  // 返回包含商品名称/价格/图片的明细
  const [itemRows] = await db.query(`
    SELECT op.product_id, op.quantity, p.name, p.price, p.image
    FROM Order_Product op
    JOIN Product p ON op.product_id = p.id
    WHERE op.order_id = ?
  `, [id]);

  const order = orderRows[0];
  order.items = itemRows;

  res.json(success(order));
};

exports.cancelOrder = async (req, res) => {
  const { id } = req.params;

  // 检查订单是否存在（修正表名）
  const [orderRows] = await db.query('SELECT * FROM `Order` WHERE id=? AND user_id=?', [id, req.user.id]);
  if (!orderRows.length) return res.json(fail('订单不存在'));

  const order = orderRows[0];
  if (order.status !== ORDER_STATUS.PREORDER) return res.json(fail('订单状态不允许取消'));

  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();

    // 更新订单状态（修正表名）
    await connection.query('UPDATE `Order` SET status = ? WHERE id = ?', [ORDER_STATUS.COMPLETED, id]);

    // 恢复库存（修正表名与字段）
    const [itemRows] = await db.query('SELECT product_id, quantity FROM Order_Product WHERE order_id=?', [id]);
    for (const item of itemRows) {
      await connection.query('UPDATE Product SET stock = stock + ? WHERE id = ?', [item.quantity, item.product_id]);
    }

    await connection.commit();
    res.json(success());
  } catch (error) {
    await connection.rollback();
    console.error(error);
    res.json(fail('取消订单失败'));
  } finally {
    connection.release();
  }
};